﻿using System.Text;
using System.Text.Json;
using Microsoft.IdentityModel.Tokens;
using TokenApi.Contract;

namespace TokenApi.Service.Infrastructure;

public static class TokenHttpClient
{
    public static async Task<HttpResponseMessage> HttpRequestRaw(this HttpClient httpClient, string url,
        object? postData,
        string token)
    {
        HttpRequestMessage req = new(HttpMethod.Post, url);

        if (postData != null)
        {
            if (postData is HttpContent data)
            {
                req.Content = data;
            }
            else
            {
                string jsonContent = JsonSerializer.Serialize(postData, new JsonSerializerOptions
                {
                    IgnoreNullValues = true
                });
                var stringContent = new StringContent(jsonContent, Encoding.UTF8, "application/json");
                req.Content = stringContent;
            }
        }

        if (!token.IsNullOrEmpty())
        {
            req.Headers.Add("Authorization", $"Bearer {token}");
        }


        var response = await httpClient.SendAsync(req, HttpCompletionOption.ResponseHeadersRead);

        if (response.IsSuccessStatusCode)
        {
            return response;
        }

        var resultAsString = await response.Content.ReadAsStringAsync();
        try
        {
            var result = JsonSerializer.Deserialize<ChatCompletionDto>(resultAsString);
            response.Dispose();
            switch (result?.error.code)
            {
                case "context_length_exceeded":
                    throw new Exception("您发送的消息过长，或携带的上文过多，请减少上文数量或发送内容。");
                case "rate_limit_exceeded":
                    throw new Exception("服务负载过高，请稍后再试。");
                case "model_not_found":
                    throw new Exception("模型不存在，请联系管理员。");
            }

            if (result?.error.message.IsNullOrEmpty() == false)
            {
                throw new Exception(result.error.message);
            }
        }
        catch (Exception e)
        {
            throw new HttpRequestException(resultAsString, e);
        }

        throw new HttpRequestException(resultAsString);
    }
}